#include "tcpclient.h"
#include <QSettings>
#include <QCoreApplication>

TcpClient::TcpClient(QObject *parent) : QObject(parent)
{

    mp_clientSocket = new QTcpSocket();


    connect(mp_clientSocket, SIGNAL(readyRead()), this, SLOT(ClientRecvData()));
}

void  TcpClient::linkServer()
{
    //使用配——方便修改配置 时重连生效
    QString  m_qstrFileName = QCoreApplication::applicationDirPath() + "/config/MinddlewareConfig.ini";
    QSettings * m_psetting = new QSettings(m_qstrFileName, QSettings::IniFormat);
    this->ip = m_psetting->value(QString("/%1/%2").arg("INFO").arg("ip"),"172.0.0.1").toString();
    this->port = m_psetting->value(QString("/%1/%2").arg("INFO").arg("port"),6601).toInt();
    int relink = m_psetting->value(QString("/%1/%2").arg("INFO").arg("relink"),30000).toInt();

    mp_clientSocket->connectToHost(ip,port);
    if(!mp_clientSocket->waitForConnected(relink))
    {
        this->isconnent=false;
        emit ConnentState(isconnent);
        //连接失败 重连
        this->relink();
        return;
    }
    this->isconnent=true;

    if(tempDatas.count()>0){
        QMapIterator<int, QString> i(tempDatas);
        while (i.hasNext())
            sendMessage(i.value(),i.key());
    }

    emit ConnentState(isconnent);
}

void  TcpClient::relink(){
    emit ConnentState(isconnent);

    if(isconnent)
        mp_clientSocket->close();

    this->linkServer();
}

///
/// \brief TcpClient::ClientRecvData
///自动接收信息
void TcpClient::ClientRecvData(){
    //      if(mp_clientSocket->canReadLine()){
    //        QByteArray datas= mp_clientSocket->readLine();
    //         QString msg(datas);
    //         emit
    //      }

    char recvMsg[1024] = {0};
    int recvRe = mp_clientSocket->read(recvMsg, 1024);
    if(recvRe == -1)
    {
        this->relink();
        return;
    }
    QString *showQstr =new QString(recvMsg);

    emit RecvMessage(showQstr);

}
///
/// \brief TcpClient::sendMessage
/// \param msg
/// \param overid 是否重发编号
///
void TcpClient::sendMessage(const QString &msg, int overid){
    QString sendMsg =msg;
    char sendMsgChar[1024] = {0};
    strcpy_s(sendMsgChar, sendMsg.toStdString().c_str());
    int sendRe = mp_clientSocket->write(sendMsgChar, strlen(sendMsgChar));
    if(sendRe == -1)
    {
        //发送失败
        this->isconnent=false;

        if(overid==0)
            this->tempDatas[sendid]= sendMsg;

        this->relink();
        return;
    }

    if(tempDatas.count()>0 && overid>0){
        tempDatas.remove(overid);
    }

    sendid++;
}
